import React, { useState, useEffect } from 'react'
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  Typography, 
  Space, 
  Alert, 
  Divider,
  Row,
  Col,
  Checkbox,
  notification,
} from 'antd'
import { 
  UserOutlined, 
  LockOutlined, 
  LoginOutlined,
  UserAddOutlined,
} from '@ant-design/icons'
import { useNavigate, Link, useLocation } from 'react-router-dom'
import { useMutation } from 'react-query'
import { authApi, UserLogin, authUtils } from '../services/auth'

const { Title, Text, Paragraph } = Typography

const Login: React.FC = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const [form] = Form.useForm()
  const [rememberMe, setRememberMe] = useState(false)

  // 检查是否有来自注册页面的成功消息
  useEffect(() => {
    if (location.state?.message) {
      notification.success({
        message: '注册成功',
        description: location.state.message,
        duration: 5,
      })
    }
  }, [location.state])

  // 登录mutation
  const loginMutation = useMutation(authApi.login, {
    onSuccess: (data) => {
      // 保存用户信息
      if (data.user) {
        authUtils.saveUser(data.user)
      }
      
      // 如果选择记住密码，保存到localStorage
      if (rememberMe) {
        const formValues = form.getFieldsValue()
        localStorage.setItem('remembered_username', formValues.username)
      } else {
        localStorage.removeItem('remembered_username')
      }
      
      // 重定向到原来的页面或首页
      const from = location.state?.from || '/'
      navigate(from, { replace: true })
    },
    onError: (error: any) => {
      console.error('登录失败:', error)
    },
  })

  // 处理登录
  const handleLogin = async (values: UserLogin) => {
    await loginMutation.mutateAsync(values)
  }

  // 组件挂载时检查是否有记住的用户名
  React.useEffect(() => {
    const rememberedUsername = localStorage.getItem('remembered_username')
    if (rememberedUsername) {
      form.setFieldValue('username', rememberedUsername)
      setRememberMe(true)
    }
  }, [form])

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px',
    }}>
      <Row style={{ width: '100%', maxWidth: 1200 }}>
        <Col xs={24} md={12} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ textAlign: 'center', color: 'white', padding: '40px' }}>
            <Title level={1} style={{ color: 'white', fontSize: '3rem', marginBottom: '20px' }}>
              设备管理系统
            </Title>
          </div>
        </Col>
        
        <Col xs={24} md={12} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Card
            style={{
              width: '100%',
              maxWidth: 400,
              boxShadow: '0 10px 30px rgba(0, 0, 0, 0.3)',
              borderRadius: '12px',
            }}
          >
            <div style={{ textAlign: 'center', marginBottom: '30px' }}>
              <Title level={2} style={{ color: '#1890ff', marginBottom: '8px' }}>
                欢迎登录
              </Title>
              <Text type="secondary">请输入您的账号密码</Text>
            </div>

            {loginMutation.error && (
              <Alert
                message="登录失败"
                description={(loginMutation.error as any)?.message || '用户名或密码错误'}
                type="error"
                style={{ marginBottom: '20px' }}
                showIcon
              />
            )}

            <Form
              form={form}
              name="login"
              onFinish={handleLogin}
              layout="vertical"
              size="large"
            >
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: '请输入用户名!' },
                  { min: 3, message: '用户名至少3个字符!' },
                ]}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="用户名"
                  allowClear
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: '请输入密码!' },
                  { min: 6, message: '密码至少6个字符!' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="密码"
                  allowClear
                />
              </Form.Item>

              <Form.Item>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Checkbox 
                    checked={rememberMe} 
                    onChange={(e) => setRememberMe(e.target.checked)}
                  >
                    记住用户名
                  </Checkbox>
                  <Link to="/forgot-password" style={{ color: '#1890ff' }}>
                    忘记密码?
                  </Link>
                </div>
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loginMutation.isLoading}
                  icon={<LoginOutlined />}
                  block
                  style={{ height: '45px', fontSize: '16px' }}
                >
                  登录
                </Button>
              </Form.Item>
            </Form>

            <Divider>或</Divider>

            <div style={{ textAlign: 'center' }}>
              <Space direction="vertical" size="middle">
                <Button
                  icon={<UserAddOutlined />}
                  onClick={() => navigate('/register')}
                  block
                  style={{ height: '40px' }}
                >
                  注册新账户
                </Button>
                
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  登录即表示您同意我们的服务条款和隐私政策
                </Text>
              </Space>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default Login